#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os, sys, urllib2, json, time, md5
from os import path


#  http://v.ifeng.com/live/js/scheduleurlall.js
#  http://live.ifeng.com/liveAllocation.do?cid=4AC51C17-9FBE-47F2-8EE0-8285A66EAFF5&t=1374816786274 - > {"link":"http://ifenglive.soooner.com/?uuid=5B63686E5D445830303030303034327C3130303031317C7C7C7C72746D707C666C765B2F63686E5D5B74735D315B2F74735D5B7375735D315B2F7375735DVSDNSOOONERCOM00|js","cid":"4AC51C17-9FBE-47F2-8EE0-8285A66EAFF5","cdnid":"Sooner"}
#  http://ifenglive.soooner.com/?uuid=5B63686E5D445830303030303034327C3130303031317C7C7C7C72746D707C666C765B2F63686E5D5B74735D315B2F74735D5B7375735D315B2F7375735DVSDNSOOONERCOM00&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=1374817087&ifenv=1&ifensg=3708b7d90f&ifenuserid=
# -> var playurl="rtmp://218.29.173.35:1755/157/50703/100011?swax_k=_ver_tm_ar_sig&swax_v=_1.0_1374827589_1687_b94acf2bb5";goOn(playurl);



#&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=1375081621&ifenv=1&ifensg=812dfd5e34&ifenuserid=
#&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=1374817087&ifenv=1&ifensg=3708b7d90f&ifenuserid=

#return param1 + "&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=" + int(new Date().time / 1000 + 300) + "&ifenv=1&ifensg=" + MD5.hash("ifeng" + "7171537bdc0b95c6a23d9e21ea6615ebet720se2zjw" + int(new Date().time / 1000 + 300) + param1 + "1" + "ifenuserid=").substring(5, 15) + "&ifenuserid=";
#return param1 + "&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=" + int(new Date().time / 1000 + 300) + "&ifenv=1&ifensg=" + MD5.hash("ifeng" + "7171537bdc0b95c6a23d9e21ea6615ebet720se2zjw" + int(new Date().time / 1000 + 300) + param1 + "1" + "ifenuserid=").substring(5, 15) + "&ifenuserid=";

def win32_unicode_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i] for i in
                xrange(start, argc.value)]

def mhash(uid):
    now = str(int(time.time() + 300))
    return "&swax_rt=js&ifenai=ifeng&ifenfg=&ifents=" + \
            now + \
            "&ifenv=1&ifensg=" + \
            md5.new( 
                "ifeng" + "7171537bdc0b95c6a23d9e21ea6615ebet720se2zjw" + now + uid + "1" + "ifenuserid=" 
            ).hexdigest()[5:15] + \
            "&ifenuserid="

sys.argv = win32_unicode_argv()
header = {'Referer': 'http://http://v.ifeng.com/live', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0'}
req =  urllib2.Request("http://v.ifeng.com/live/js/scheduleurlall.js",headers=header)
data = urllib2.urlopen(req).read()
data = data[data.find('{'):data.rfind('}')+1]
data = data.replace("'",'"')
jdic = json.loads(data)
target = min([a['url'] for a in jdic.itervalues() if a['name'].find(sys.argv[1]) >= 0 ])
uuid = target[target.find('=')+1:target.rfind('|js')]
target = target[0:target.rfind('|js')] + mhash(uuid)
req =  urllib2.Request(target,headers=header)
data = urllib2.urlopen(req).read()
rtmp = data[data.find('rtmp'):data.rfind('"')]
#print(rtmp)
if len(sys.argv) > 2:
    os.spawnv(os.P_NOWAIT, sys.argv[2], [path.basename(sys.argv[2])] + sys.argv[3:] + [rtmp])
else:
    print(rtmp)

